package com.wolfeyes.framework.springsecurity.handle;

import com.wolfeyes.framework.springsecurity.domain.model.SysPermission;

import lombok.extern.slf4j.Slf4j;

import com.wolfeyes.framework.service.SysPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @description springSecurity中的FilterInvocationSecurityMetadataSource 安全元数据 和 访问决策管理器AccessDecisionManager，
 * @description 这两个是非常重要的，因为可以实现基于JDBC的动态权限控制
 * @author yanyljava
 * @description 自定义安全元数据的数据源
 * @create 2021-10-24 21:06
 */
@Slf4j
@Component
public class CustomizeFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {
	
	/**
	 * @title Ant-style path patterns
	 */
	AntPathMatcher antPathMatcher = new AntPathMatcher();
	
	@Autowired
	SysPermissionService sysPermissionService;
	
	@Override
	public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
		
		log.debug("自定义的安全元数据的数据源处理器被调用 Start！");
		//获取请求地址
		String requestUrl = ((FilterInvocation) object).getRequestUrl();

		//查询具体某个接口的权限
		List<SysPermission> permissionList =  new ArrayList<>();
		//List<SysPermission> permissionList =  sysPermissionService.selectListByPath(requestUrl);
		if(permissionList == null || permissionList.size() == 0){
			//请求路径没有配置权限，表明该请求接口可以任意访问
			return null;
		}
		String[] attributes = new String[permissionList.size()];
		for(int i = 0;i<permissionList.size();i++){
			attributes[i] = permissionList.get(i).getPermissionCode();
		}
		log.debug("自定义的安全元数据的数据源处理器被调用 End！");
		return SecurityConfig.createList(attributes);
	}

	@Override
	public Collection<ConfigAttribute> getAllConfigAttributes() {
		
		return null;
	}

	@Override
	public boolean supports(Class<?> aClass) {
		
		return true;
	}
	
}


